﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace ES.Client
{
    public static class ISearchResponseExt
    {
        /// <summary>
        /// 获取高亮文档
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="response"></param>
        /// <returns></returns>
        public static List<T> GetHighlightedDocuments<T>(this Nest.ISearchResponse<T> response) where T : class,new()
        {
            var documents = new List<T>();

            if (!response.IsValid)
            {
                return documents;
            }

            if (response.Total <= 0)
            {
                return documents;
            }

            if (!response.Hits.Any())
            {
                return documents;
            }

            var hits = response.Hits.ToList();
            foreach (var hit in hits)
            {
                var source = hit.Source ?? new T();

                try
                {
                    var rawObject = JObject.FromObject(source);
                    JObject highlightObject = new JObject();
                    var highlights = hit.Highlights.Select(t => t.Value).ToList();
                    foreach (var highlight in highlights)
                    {
                        try
                        {
                            var field = highlight.Field;
                            var field_value = highlight.Highlights.FirstOrDefault();
                            highlightObject.Add(field, field_value);
                        }
                        catch
                        {
                            continue;
                        }
                    }

                    rawObject.Merge(highlightObject);
                    documents.Add(rawObject.ToObject<T>());
                }
                catch
                {
                    documents.Add(source);
                    continue;
                }
            }

            return documents;
        }
    }
}
